/* 指尖血糖js处理⬇ */

var url = location.origin;
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
$("#bloodSearchInput").val((new Date()).Format("yyyy-MM"));
var FBG = {
        //页面初始化；
        pre_meal_s: null,
        pre_meal_l: null,
        after_meal_s: null,
        after_meal_l: null,
        before_bed_s: null,
        before_bed_l: null,
        wee_hours_s: null,
        wee_hours_l: null,
        dataFBG: null,
        init: function () {
            setTimeout(function () {
                //获取血糖值接口
                ajax('get', url + '/dynamic/bloodContrast/getList', {
                    user_id: $("#user_id").val(),
                }, FBG.getListBack);


                //获取表格血糖数据接口
                ajax('get', url + '/dynamic/bloodTest/byTime', {
                    user_id: $("#user_id").val(),
                    t: $("#bloodSearchInput").val()
                }, FBG.FBGDataCallBack);


            }, 100)
        },
        FBGDataCallBack: function (data) {
            var tableBody = $("#ChartTable tbody");
            // var myChart = echarts.init(document.getElementById('FBGChart1'));//双周血糖暂时不要
            var myChart2 = echarts.init(document.getElementById('FBGChart2'));
            if (data.code == 10000) {
                var dataFBG = {
                    minDate: "2017-11-08",
                    // maxDate: "2017-11-30",
                    data: [],
                };
                // dataFBG.minDate=data.data.minDate;//将查询首日期赋值到dataFBG对象中
                // dataFBG.data=data.data.boold_table;//图标数据
                // dataFBG.EmptyNormal=data.data.EmptyNormal;//图标数据

                dataFBG = data.data;
                // this.dataFBG = dataFBG;
                $.each($(".emptyFBG").find("input"), function (k, v) {
                    if (!FBG["v" + Number(k + 1)]) {
                        (k % 2) ? $(v).val(50) : $(v).val(1);
                    } else {
                        $(v).val((FBG["v" + Number(k + 1)]));
                    }
                });

                $.each($(".afterMealFBG").find("input"), function (k, v) {
                    if (!FBG["vv" + Number(k + 1)]) {
                        (k % 2) ? $(v).val(50) : $(v).val(1);

                    } else {
                        $(v).val(FBG["vv" + Number(k + 1)]);
                    }

                });
                var tableHtml = '';
                var m = 0;
                var now = new Date();
                var nowYear = now.getFullYear(); //得到年份
                var nowMonth = now.getMonth();//得到月份
                var nowDate = now.getDate();//得到日期
                $.each(dataFBG.boold_table, function (k, v) {
                    tableHtml += '<tr>' +
                        '<td><input disabled class="dateInput BGInput" type="text" value="' + FBG.globalFun.addDate(dataFBG.minDate, m) + '"></td>' +
                        '<td style="color:' + FBG.globalFun.checkTableColor(v[0], FBG.pre_meal_s, FBG.pre_meal_l) + '"><input data-type="1" class="BGInput emp numberStrict" type="" value="' + FBG.checkNull(v[0]) + '"></td>' +
                        '<td style="color:' + FBG.globalFun.checkTableColor(v[1], FBG.after_meal_s, FBG.after_meal_l) + '"><input data-type="2" class="BGInput eat" type="" value="' + FBG.checkNull(v[1]) + '"></td>' +
                        '<td style="color:' + FBG.globalFun.checkTableColor(v[2], FBG.pre_meal_s, FBG.pre_meal_l) + '"><input data-type="3" class="BGInput emp" type="" value="' + FBG.checkNull(v[2]) + '"></td>' +
                        '<td style="color:' + FBG.globalFun.checkTableColor(v[3], FBG.after_meal_s, FBG.after_meal_l) + '"><input data-type="4" class="BGInput eat" type="" value="' + FBG.checkNull(v[3]) + '"></td>' +
                        '<td style="color:' + FBG.globalFun.checkTableColor(v[4], FBG.pre_meal_s, FBG.pre_meal_l) + '"><input data-type="5" class="BGInput emp" type="" value="' + FBG.checkNull(v[4]) + '"></td>' +
                        '<td style="color:' + FBG.globalFun.checkTableColor(v[5], FBG.after_meal_s, FBG.after_meal_l) + '"><input data-type="6" class="BGInput eat" type="" value="' + FBG.checkNull(v[5]) + '"></td>' +
                        '<td style="color:' + FBG.globalFun.checkTableColor(v[6], FBG.before_bed_s, FBG.before_bed_l) + '"><input data-type="7" class="BGInput emp" type="" value="' + FBG.checkNull(v[6]) + '"></td>' +
                        '<td style="border-right:none;color:' + FBG.globalFun.checkTableColor(v[7], FBG.wee_hours_s, FBG.wee_hours_l) + '"><input data-type="8" class="BGInput emp" type="" value="' + FBG.checkNull(v[7]) + '"></td>' +
                        '</tr>';
                    m++;

                    if((Number(m) >= Number(nowDate)) && (Number(nowYear) == Number($("#bloodSearchInput").val().slice(0, 4))) && (Number(nowMonth+1) == Number($("#bloodSearchInput").val().slice(-2)))){
                        return false
                    }


                });
                tableBody.html(tableHtml);
                // myChart.setOption(FBG.chartInit(dataFBG, 'doubleWeek'));//双周血糖暂时不要
                myChart2.setOption(FBG.chartInit(dataFBG.boold_table));
            } else {
                alertModel("温馨提示", data.message)
            }
            FBG.control();
        },
        getListBack: function (data) {
            "use strict";
            // console.log(data);
            if (data.code == 10000) {

                $.each(data.data, function (k, v) {
                    switch (v.type) {
                        case 1:
                            FBG.pre_meal_s = (v.min_value ? v.min_value : 3.9);
                            $("input.pre_meal_s").val(v.min_value ? v.min_value : 3.9);
                            FBG.pre_meal_l = (v.max_value ? v.max_value : 6.1);
                            $("input.pre_meal_l").val(v.max_value ? v.max_value : 6.1);
                            break;
                        case 2:
                            FBG.after_meal_s = (v.min_value ? v.min_value : 4.4);
                            $("input.after_meal_s").val(v.min_value ? v.min_value : 4.4);

                            FBG.after_meal_l = (v.max_value ? v.max_value : 7.8);
                            $("input.after_meal_l").val(v.max_value ? v.max_value : 7.8);
                            break;
                        case 3:
                            FBG.before_bed_s = (v.min_value ? v.min_value : 3.9);
                            $("input.before_bed_s").val(v.min_value ? v.min_value : 3.9);
                            FBG.before_bed_l = (v.max_value ? v.max_value : 6.1);
                            $("input.before_bed_l").val(v.max_value ? v.max_value : 6.1);
                            break;
                        case 4:
                            FBG.wee_hours_s = (v.min_value ? v.min_value : 3.9);
                            $("input.wee_hours_s").val(v.min_value ? v.min_value : 3.9);
                            FBG.wee_hours_l = (v.max_value ? v.max_value : 6.1);
                            $("input.wee_hours_l").val(v.max_value ? v.max_value : 6.1);
                            break;
                    }


                });

                //获取统计接口⬇
                ajax('get', url + '/dynamic/bloodTest/statistics', {
                    user_id: $("#user_id").val(),
                }, FBG.statisticsBack);

            } else {
                if($(".modal-dialog").css("display")!=='block'){
                    alertModel('温馨提示', data.message)
                }

            }

        },
        statisticsBack: function (data) {

            if (data.code == 10000) {
                //一周
                $(".probability .week .average .value").html(Number(data.data.week_array.week_avg).toFixed(1));
                $(".probability .week .times .value").html(data.data.week_array.week_count);
                $(".probability .week .cir .value.n span").html(data.data.week_array.normal);
                $(".probability .week .cir .value.h span").html(data.data.week_array.high);
                $(".probability .week .cir .value.l span").html(data.data.week_array.low);
                $(".probability .week .percen.n").html(FBG.isNaNSelf((data.data.week_array.normal / data.data.week_array.week_count * 100)).toFixed(1) + "%");
                $(".probability .week .percen.h").html(FBG.isNaNSelf((data.data.week_array.high / data.data.week_array.week_count * 100)).toFixed(1) + "%");
                $(".probability .week .percen.l").html(FBG.isNaNSelf((data.data.week_array.low / data.data.week_array.week_count * 100)).toFixed(1) + "%");


                //一月
                $(".probability .oneMonth .average .value").html(Number(data.data.month_array.month_avg).toFixed(1));
                $(".probability .oneMonth .times .value").html(data.data.month_array.month_count);
                $(".probability .oneMonth .cir .value.n span").html(data.data.month_array.normal);
                $(".probability .oneMonth .cir .value.h span").html(data.data.month_array.high);
                $(".probability .oneMonth .cir .value.l span").html(data.data.month_array.low);
                $(".probability .oneMonth .percen.n").html(FBG.isNaNSelf((data.data.month_array.normal / data.data.month_array.month_count * 100)).toFixed(1) + "%");
                $(".probability .oneMonth .percen.h").html(FBG.isNaNSelf((data.data.month_array.high / data.data.month_array.month_count * 100)).toFixed(1) + "%");
                $(".probability .oneMonth .percen.l").html(FBG.isNaNSelf((data.data.month_array.low / data.data.month_array.month_count * 100)).toFixed(1) + "%");

                //三月
                $(".probability .threeMonth .average .value").html(Number(data.data.three_month_array.three_avg).toFixed(1));
                $(".probability .threeMonth .times .value").html(data.data.three_month_array.three_month_count);
                $(".probability .threeMonth .cir .value.n span").html(data.data.three_month_array.normal);
                $(".probability .threeMonth .cir .value.h span").html(data.data.three_month_array.high);
                $(".probability .threeMonth .cir .value.l span").html(data.data.three_month_array.low);
                $(".probability .threeMonth .percen.n").html(FBG.isNaNSelf((data.data.three_month_array.normal / data.data.three_month_array.three_month_count * 100)).toFixed(1) + "%");
                $(".probability .threeMonth .percen.h").html(FBG.isNaNSelf((data.data.three_month_array.high / data.data.three_month_array.three_month_count * 100)).toFixed(1) + "%");
                $(".probability .threeMonth .percen.l").html(FBG.isNaNSelf((data.data.three_month_array.low / data.data.three_month_array.three_month_count * 100)).toFixed(1) + "%");


            } else {
                if($(".modal-dialog").css("display")!=='block'){
                    alertModel('温馨提示', data.message)
                }

            }
        },
        isNaNSelf: function (data) {

            if (isNaN(data)) {
                return 0
            } else {
                return data
            }
        },
        // 页面的控制
        control: function () {
            //有关血糖范围值设定对象⬇
            var EmptyRange = {
                fbg: $("#FBG"),
                fbgRangeUl: $("#FBG").find(".FBGRange ul"),
                fbgRangeLis: $("#FBG").find(".FBGRange ul li"),
                //为所有的血糖范围input框绑定blur事件
                rangeBind: function () {
                    $.each(this.fbgRangeLis.find("input"), function (k, v) {
                        $(v).unbind().bind("blur", function () {
                            EmptyRange.rangeCheck($(v));
                        })
                    });

                },
                //检查input框输入的值是否合理
                rangeCheck: function ($dom) {
                    if ($dom.hasClass("small")) {
                        if (($dom.val() === "") || (Number($dom.val()) < 1) || (Number($dom.val()) > 50) || Number($dom.siblings("input.large").val()) < Number($dom.val())) {
                            alertModel("温馨提示", "血糖值输入值不合理，请重新输入", '确定');
                            $dom.val("1");
                        }
                    } else {
                        if (($dom.val() === "") || (Number($dom.val()) < 1) || (Number($dom.val()) > 50) || (Number($dom.siblings("input.small").val()) > Number($dom.val()))) {
                            alertModel("温馨提示", "血糖值输入值不合理，请重新输入");
                            $dom.val("50");
                        }
                    }

                },


            };
            //保存按钮
            var Save = {
                    saveBtn: $(".FBGRange .FBGRangeSave"),
                    saveFun: function () {
                        this.saveBtn.unbind().click(function () {
                                $.each($(".emptyFBG").find("input"), function (k, v) {
                                    // $(v).val(FBG["v" + Number(k + 1)]);
                                    FBG["v" + Number(k + 1)] = $(v).val()
                                });
                                $.each($(".afterMealFBG").find("input"), function (k, v) {
                                    // $(v).val(FBG["vv" + Number(k + 1)]);
                                    FBG["vv" + Number(k + 1)] = $(v).val()
                                });

                                var obj = {
                                    user_id: $("#user_id").val(),
                                    contrast: [{}, {}, {}, {}]
                                };
                                obj.contrast[0]["type"] = 1;
                                obj.contrast[0]["min_value"] = $("input.pre_meal_s").val();
                                obj.contrast[0]["max_value"] = $("input.pre_meal_l").val();
                                obj.contrast[1]["type"] = 2;
                                obj.contrast[1]["min_value"] = $("input.after_meal_s").val();
                                obj.contrast[1]["max_value"] = $("input.after_meal_l").val();
                                obj.contrast[2]["type"] = 3;
                                obj.contrast[2]["min_value"] = $("input.before_bed_s").val();
                                obj.contrast[2]["max_value"] = $("input.before_bed_l").val();
                                obj.contrast[3]["type"] = 4;
                                obj.contrast[3]["min_value"] = $("input.wee_hours_s").val();
                                obj.contrast[3]["max_value"] = $("input.wee_hours_l").val();

                                ajax('post', url + '/dynamic/bloodContrast/store', obj, rangeCallBack);

                                function rangeCallBack(data) {
                                    if (data.code == 10000) {
                                        alertModel('温馨提示', '保存成功！');
                                        FBG.init();
                                    } else {
                                        if($(".modal-dialog").css("display")!=='block'){
                                            alertModel('温馨提示', data.message)
                                        }

                                    }

                                };

                            }
                        );
                    },
//血糖正常、高、异常高 范围保存交互前处理方法⬇️
                    rangeValProcess: function (times) {
                        var emptyFBG = $(".emptyFBG");
                        var afterMealFBG = $(".afterMealFBG");
                        var rangeObj;
                        if (times == 1) {
                            rangeObj = {};
                            rangeObj.greenlow = emptyFBG.find("input.greenS").val();
                            rangeObj.greenhigh = emptyFBG.find("input.greenL").val();
                            rangeObj.yellowlow = emptyFBG.find("input.yellowS").val();
                            rangeObj.yellowhigh = emptyFBG.find("input.yellowL").val();
                            rangeObj.redlow = emptyFBG.find("input.redS").val();
                            rangeObj.redhigh = emptyFBG.find("input.redL").val();
                            rangeObj.gettimetype = 1;
                            rangeObj.user_id = $("#user_id").val();
                            return rangeObj
                        } else {
                            rangeObj = {};
                            rangeObj.greenlow = afterMealFBG.find("input.greenS").val();
                            rangeObj.greenhigh = afterMealFBG.find("input.greenL").val();
                            rangeObj.yellowlow = afterMealFBG.find("input.yellowS").val();
                            rangeObj.yellowhigh = afterMealFBG.find("input.yellowL").val();
                            rangeObj.redlow = afterMealFBG.find("input.redS").val();
                            rangeObj.redhigh = afterMealFBG.find("input.redL").val();
                            rangeObj.gettimetype = 2;
                            rangeObj.user_id = $("#user_id").val();
                            return rangeObj

                        }
                    }

                }
            ;

//table中数据的修改
            var mainTableValChange = {
                table: $("#ChartTable"),
                input: $("#ChartTable").find('input.BGInput'),
                changeSave: function () {
                    $.each(this.input, function (k, v) {
                        $(v).change(function () {
                            $(v).val(checkMInMax($(v).val(), 1, 50, 1));
                            var obj = {
                                t: $(v).parents('tr').find('input.dateInput').val(),
                                TYPE: $(v).attr('data-type') - 1,
                                COUNTS: $(v).val(),
                                user_id: $("#user_id").val(),
                            };

                            ajax('post', url + '/dynamic/bloodTest/edit', obj, function (data) {
                                if (data.code == 10000) {
                                    FBG.init();
                                } else {
                                    if($(".modal-dialog").css("display")!=='block'){
                                        alertModel('温馨提示', data.message)
                                    }

                                }
                            })
                        })
                    })
                }
            };

// 为切换静态和动态血糖绑定事件
            $(".bgTab").unbind().bind('click', function () {
                $(this).parent('li').siblings('li').removeClass('active').end().addClass('active');
                if (this.id === 'dbgTab') {
                    // $("#BG").load('DBG.html');
                    $("#FBG").hide();
                    $("#DBG").show();
                    $(self).siblings("li#BGChart").removeClass("active").end().addClass("active");
                    DBGOBJ.init();

                } else {
                    // $.cookie('SUITANG_BG', 'FBG');
                    $("#FBG").show();
                    $("#DBG").hide();
                }
                $("#RBGModel,#printModel").fadeOut("normal");
            });

// //取cookie值，判断默认点在那个tab上；
            if ($('.bgTab').eq(0).parent('li').hasClass('active')) {
                $(".bgTab").eq(0).click();
            } else {
                $(".bgTab").eq(1).click();
            }

            $("#bloodSearchInput").unbind('click').bind('click', function () {
                $(".table-condensed").off().delegate(".month", 'click', function () {
                    setTimeout(function () {
                        if ($("#bloodSearchInput").val() !== "") {
                            ajax('get', url + '/dynamic/bloodTest/byTime', {
                                user_id: $("#user_id").val(),
                                t: $("#bloodSearchInput").val()
                            }, function (data) {
                                if (data.code = 10000) {
                                    FBG.FBGDataCallBack(data)
                                    $("ul.showType li.active").click();
                                } else {
                                    if($(".modal-dialog").css("display")!=='block'){
                                        alertModel('温馨提示', data.message)
                                    }

                                }
                            })
                        }
                    }, 100);
                });


            });


            EmptyRange.rangeBind();
            Save.saveFun();
            mainTableValChange.changeSave();//为table中的input绑定change事件


//静态血糖、饮食、用药、胰岛素、运动 切换⬇️
            $("ul.showType li").unbind('click').bind('click', function () {
                $("ul.showType li").removeClass("active");
                $(this).addClass('active');
                FBG.eventChange($(this).attr('data-name'))
            });
            $("#export").unbind().bind('click', function () {
                var jsono = [];
                $.each($("#ChartTable tbody.ChartTbody tr"), function (k, v) {
                    var obj = {
                        date: $(v).find('input').eq(0).val(),
                        pre_meal_f: $(v).find('input').eq(1).val(),
                        after_meal_f: $(v).find('input').eq(2).val(),
                        pre_meal_l: $(v).find('input').eq(3).val(),
                        after_meal_l: $(v).find('input').eq(4).val(),
                        pre_meal_d: $(v).find('input').eq(5).val(),
                        after_meal_d: $(v).find('input').eq(6).val(),
                        before_bed: $(v).find('input').eq(7).val(),
                        wee_hours: $(v).find('input').eq(8).val()
                    };
                    jsono.push(obj)
                });

                downloadExl(jsono);

                var tmpDown; //导出的二进制对象
                function downloadExl(json, type) {
                    var tmpdata = json[0];
                    // var tmpdata = json;
                    json.unshift({});
                    var keyMap = []; //获取keys
                    for (var k in tmpdata) {
                        keyMap.push(k);
                        json[0][k] = ((k === 'date') && (k = "日期"));
                        json[0][k] = ((k === 'pre_meal_f') && (k = "早餐前"));
                        json[0][k] = ((k === 'after_meal_f') && (k = "早餐后"));
                        json[0][k] = ((k === 'pre_meal_l') && (k = "午餐前"));
                        json[0][k] = ((k === 'after_meal_l') && (k = "午餐后"));
                        json[0][k] = ((k === 'pre_meal_d') && (k = "晚餐前"));
                        json[0][k] = ((k === 'after_meal_d') && (k = "晚餐后"));
                        json[0][k] = ((k === 'before_bed') && (k = "睡前"));
                        json[0][k] = ((k === 'wee_hours') && (k = "凌晨"));

                    }
                    var tmpdata = [];//用来保存转换好的json

                    //将es6装换成es5 代码 ⬇️
                    json.map(function (v, i) {

                        return keyMap.map(function (k, j) {

                            return Object.assign({}, {
                                v: v[k],
                                position: (j > 25 ? getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
                            });

                        });
                    }).reduce(function (prev, next) {
                        return prev.concat(next);
                    }).forEach(function (v, i) {

                        return tmpdata[v.position] = {v: checkUndefined(v.v)};

                    });
                    //将es6装换成es5 代码⬆️

                    var outputPos = Object.keys(tmpdata); //设置区域,比如表格从A1到D10

                    var tmpWB = {
                        // SheetNames: ['mySheet'], //保存的表标题
                        SheetNames: ['mySheet'], //保存的表标题
                        Sheets: {
                            'mySheet': Object.assign({},
                                tmpdata, //内容
                                {
                                    '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] //设置填充区域
                                })
                        }
                    };
                    tmpDown = new Blob([s2ab(XLSX.write(tmpWB,
                        {bookType: (type == undefined ? 'xlsx' : type), bookSST: false, type: 'binary'}//这里的数据是用来定义导出的格式类型
                    ))], {
                        type: ""
                    }); //创建二进制对象写入转换好的字节流
                    var href = URL.createObjectURL(tmpDown); //创建对象超链接
                    document.getElementById("hf").href = href; //绑定a标签
                    document.getElementById("hf").click(); //模拟点击实现下载
                    setTimeout(function () { //延时释放
                        URL.revokeObjectURL(tmpDown); //用URL.revokeObjectURL()来释放这个object URL
                    }, 100);
                }

                function s2ab(s) { //字符串转字符流
                    var buf = new ArrayBuffer(s.length);
                    var view = new Uint8Array(buf);
                    for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                    return buf;
                }

                // 将指定的自然数转换为26进制表示。映射关系：[0-25] -> [A-Z]。
                function getCharCol(n) {
                    var temCol = '',
                        s = '',
                        m = 0;
                    while (n > 0) {
                        m = n % 26 + 1;
                        s = String.fromCharCode(m + 64) + s;
                        n = (n - m) / 26
                    }
                    return s
                }

            })


        },

        eventChange: function (name) {
            if (name) {
                $("#contentSwitch>div." + name).show();
                $("#contentSwitch>div").not('.' + name).hide();
            }


            var DietObj = {
                user_id: $("#user_id").val(),
                t: $("#bloodSearchInput").val()
            };
            var DrugObj = {
                user_id: $("#user_id").val(),
                t: $("#bloodSearchInput").val(),
                type: 1
            };
            var InsulinObj = {
                user_id: $("#user_id").val(),
                t: $("#bloodSearchInput").val(),
                type: 0
            };
            if (name == 'Diet') {
                ajax('get', url + '/dynamic/bloodDiet/getListByTime', DietObj, dietFun);//饮食
            } else if (name == 'Drug') {
                ajax('get', url + '/dynamic/bloodMedication/getListByTime', DrugObj, DrugFun);//用药
            } else if (name == 'Insulin') {
                ajax('get', url + '/dynamic/bloodMedication/getListByTime', InsulinObj, InsulinFun);//胰岛素
            } else if (name == 'motion') {
                ajax('get', url + '/dynamic/bloodMotion/getListByTime', DietObj, motionFun);//运动
            } else {

            }

        }
        ,


        globalFun: {

            addDate: function (date, days) {
                var d = new Date(date.slice(0, 10));
                d.setDate(d.getDate() + Number(days));
                var m = d.getMonth() + 1;
                return d.getFullYear() + '-' + m + '-' + d.getDate();
            }
            ,
            //检测餐前血糖的范围，返回颜色
            checkTableColor: function (value, sVal, lVal) {//参数：1.表格的数值、2.血糖自定义最小值、3.血糖自定义最大值

                if (value !== "") {
                    // if (Number(value) < Number(v6) && Number(value) >= Number(v5)) {
                    if (Number(value) > Number(lVal)) {
                        return "#ED4040";
                    } else if (Number(value) >= Number(sVal)) {
                        return "#65C531";
                    } else {
                        return "#2DB3C5";
                    }
                }


            }
            ,
        }
        ,
        checkNull: function (data) {
            if (data == null || data == 'null' || data == undefined) {
                return ""
            } else {
                return data
            }
        }
        ,
        chartInit: function (data, type) {
            var text = '', xAxisData = '';
            var dataArr0 = [];
            var dataArr1 = [];
            var dataArr2 = [];
            var dataArr3 = [];
            var dataArr4 = [];
            var dataArr5 = [];
            var dataArr6 = [];
            var dataArr7 = [];

            if (type === 'doubleWeek') {
                text = "双周血糖";//标题
                xAxisData = ['01', '02', '03', '04', '05', '06', "07", "08", "09", "10", "11", "12", "13", "14", "15"];//x轴坐标单位
                for (var i = 0; i < 15; i++) {
                    for (var z = 0; z < data.data[i].length; z++) {
                        switch (z) {
                            case 0:
                                dataArr0.push(data.data[i][z]);
                                break;
                            case 1:
                                dataArr1.push(data.data[i][z]);
                                break;
                            case 2:
                                dataArr2.push(data.data[i][z]);
                                break;
                            case 3:
                                dataArr3.push(data.data[i][z]);
                                break;
                            case 4:
                                dataArr4.push(data.data[i][z]);
                                break;
                            case 5:
                                dataArr5.push(data.data[i][z]);
                                break;
                            case 6:
                                dataArr6.push(data.data[i][z]);
                                break;
                            case 7:
                                dataArr7.push(data.data[i][z]);
                                break;
                        }
                    }
                }

            }
            else {
                // text = "整月血糖";
                xAxisData = ['01', '02', '03', '04', '05', '06', "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"];
                $.each(data, function (k, v) {
                    $.each(v, function (x, c) {
                        switch (x) {
                            case 0:
                                dataArr0.push(c);
                                break;
                            case 1:
                                dataArr1.push(c);
                                break;
                            case 2:
                                dataArr2.push(c);
                                break;
                            case 3:
                                dataArr3.push(c);
                                break;
                            case 4:
                                dataArr4.push(c);
                                break;
                            case 5:
                                dataArr5.push(c);
                                break;
                            case 6:
                                dataArr6.push(c);
                                break;
                            case 7:
                                dataArr7.push(c);
                                break;
                        }
                    });

                });

            }
            var result = {
                title: {
                    text: text, //一级标题
                    subtext: '',//二级标题
                    textAlign: 'center',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ["早餐前", "早餐后", "午餐前", "午餐后", "晚餐前", "晚餐后", "睡前", '凌晨'],
                    orient: 'vertical',
                    y: 'center',
                    x: 'right',
                    // itemGap:'700px'
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        // dataView: {readOnly: false},
                        magicType: {type: ['line', 'bar']},
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: xAxisData //x轴坐标单位
                },
                yAxis: {
                    name: "血糖值(mmol/L)",
                    type: 'value',
                    axisLabel: {
                        // formatter: '血糖值(mmol/L)'
                        formatter: '{value}'
                    }
                },
                series: [
                    {
                        position: 'bottom',
                        name: '早餐前',
                        type: 'line',
                        data: dataArr0,//数组每个点的值
                        markPoint: {
                            // data: [
                            //     {type: 'max', name: '最大值'},
                            //     {type: 'min', name: '最小值'}
                            // ]
                        },
                        //标记的虚线，默认为词条曲线的平均数
                        markLine: {
                            data: [
                                // {type: 'average', name: '平均值'}
                            ]
                        },
                        itemStyle: {
                            normal: {
                                color: "#6eaaee" //图标颜色

                            }
                        },
                    },
                    {
                        name: '早餐后',
                        type: 'line',
                        data: dataArr1,
                        markPoint: {
                            data: [
                                // {type: 'max', name: '最大值'},
                                // {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                // {type: 'average', name: '平均值'}
                            ]
                        }
                    },
                    {
                        name: '午餐前',
                        type: 'line',
                        data: dataArr2,
                        markPoint: {
                            data: [
                                // {type: 'max', name: '最大值'},
                                // {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                // {type: 'average', name: '平均值'}
                            ]
                        },
                        normal: {
                            color: "#6ea431" //图标颜色
                        }
                    },
                    {
                        name: '午餐后',
                        type: 'line',
                        data: dataArr3,
                        markPoint: {
                            data: [
                                // {type: 'max', name: '最大值'},
                                // {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                // {type: 'average', name: '平均值'}
                            ]
                        },
                        normal: {
                            color: "#2ea132" //图标颜色
                        }
                    },
                    {
                        name: '晚餐前',
                        type: 'line',
                        data: dataArr4,
                        markPoint: {
                            data: [
                                // {type: 'max', name: '最大值'},
                                // {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                // {type: 'average', name: '平均值'}
                            ]
                        },
                        normal: {
                            color: "#a123ac" //图标颜色
                        }
                    },
                    {
                        name: '晚餐后',
                        type: 'line',
                        data: dataArr5,
                        markPoint: {
                            data: [
                                // {type: 'max', name: '最大值'},
                                // {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                // {type: 'average', name: '平均值'}
                            ]
                        },
                        normal: {
                            color: "#d1da43" //图标颜色
                        }
                    },
                    {
                        name: '睡前',
                        type: 'line',
                        data: dataArr6,
                        markPoint: {
                            data: [
                                // {type: 'max', name: '最大值'},
                                // {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                // {type: 'average', name: '平均值'}
                            ]
                        },
                        normal: {
                            color: "#343a21" //图标颜色
                        }
                    },
                    {
                        name: '凌晨',
                        type: 'line',
                        data: dataArr7,
                        markPoint: {
                            data: [
                                // {type: 'max', name: '最大值'},
                                // {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                // {type: 'average', name: '平均值'}
                            ]
                        },
                        normal: {
                            color: "#3ea431" //图标颜色
                        }
                    },


                    // {
                    //     name:'最',
                    //     type:'line',
                    //     data:[5, 6, 6, 7, 3, 4, 3,5,7,8,9,3,5,6],
                    //     markPoint: {
                    //         data: [
                    //             {name: '周最低', value: -2, xAxis: 1, yAxis: -1.5}
                    //         ]
                    //     },
                    //     markLine: {
                    //         data: [
                    //             {type: 'average', name: '平均值'},
                    //             [{
                    //                 symbol: 'none',
                    //                 x: '100%',
                    //                 yAxis: 'max'
                    //             }, {
                    //                 symbol: 'circle',
                    //                 label: {
                    //                     normal: {
                    //                         position: 'start',
                    //                         formatter: '最大值'
                    //                     }
                    //                 },
                    //                 type: 'max',
                    //                 name: '最高点'
                    //             }]
                    //         ]
                    //     }
                    // }
                ]
            };
            return result;
        }


    }
;
FBG.init();

function dietFun(data) {
    if (data.code = 10000) {

        // var dataArr = {'018-05-12': [{}, {}, {}], '018-05-13': [{}, {}, {}]};
        var dataArr = {};//用于存储整理过的数据对象（同一天放在一个对象中）
        $.each(data.data, function (z, x) {
            if (typeof (dataArr[x.diettime.slice(0, 10)]) == 'undefined') {//用于判断数组是否存在
                dataArr[x.diettime.slice(0, 10)] = [];
                dataArr[x.diettime.slice(0, 10)].push(x);
            } else {
                dataArr[x.diettime.slice(0, 10)].push(x);
            }
        });
        var mainHtml = '';

        $.each(dataArr, function (m, n) {
            var html = '';
            var htmlHead = '';
            var htmlFoot = '';
            htmlHead = '<div class="section" data-time="' + m + '"><h4 class="caption">' + m + '</h4>' +
                '<div class="section-con">';
            htmlFoot = '</div></div>';
            $.each(n, function (k, v) {
                var imgHtml = '';
                $.each(v.dietpic, function (z, x) {
                    var style = "";
                    if (z == 0) {
                        style = "margin-left: 4rem;"
                    } else {
                        style = "margin-left: 10px"
                    }
                    imgHtml += '<div class="picBox" style="' + style + '"><a target="_blank" href="' + x + '"><img alt="" src="' + x + '"></a></div>';
                    // imgHtml += '<div class="picBox" style="' + style + '"><a target="_blank" href="/static/images/timgq.jpeg"><img data-style="" alt="" src="/static/images/timgq.jpeg"></a></div>'
                });
                html += ' <div class="item">' +
                    '     <div class="typeImg"><img src="/images/Diet.png"></div>' +
                    '     <div class="item-r">' +
                    '         <div class="timeBox"><span class="time1">' + v.diettime.slice(11) + '</span><b>' + v.diettype + '</b><span' +
                    '                     class="time2">用餐' + v.durationtime + '分钟</span>' +
                    '         </div>' +
                    '         <div class="textBox">' + v.dietsituation + '</div> <div style="clear:both"></div>' +
                    imgHtml +
                    '     </div>' +
                    ' </div>'
            });
            mainHtml += htmlHead + html + htmlFoot;


        });
        if (JSON.stringify(dataArr) == '{}') {
            $('#contentSwitch .Diet').html('<h4 style="text-align: center">暂无数据</h4>');
        } else {
            $('#contentSwitch .Diet').html(mainHtml);
        }

        // $('.Diet .item-r .picBox img').unbind().click(function () {
        //     if($(this).attr("data-style")=="w"){
        //         $(".bgCover").find("img").attr("src", $(this).attr('src')).css("width","100%");
        //
        //     }else{
        //         $(".bgCover").find("img").attr("src", $(this).attr('src')).css("height","100%");
        //
        //     }
        //     $(".bgCover").show();
        // });


    } else {
        if($(".modal-dialog").css("display")!=='block'){
            if($(".modal-dialog").css("display")!=='block'){
                alertModel('温馨提示', data.message)
            }
        }

    }
};


$(".bgCover").unbind().click(function () {
    $(".bgCover").hide();
});

function DrugFun(data) {
    if (data.code = 10000) {
        // var dataArr = {'018-05-12': [{}, {}, {}], '018-05-13': [{}, {}, {}]};
        var dataArr = {};//用于存储整理过的数据对象（同一天放在一个对象中）
        $.each(data.data, function (z, x) {
            if (typeof (dataArr[x.medicationtime.slice(0, 10)]) == 'undefined') {//用于判断数组是否存在
                dataArr[x.medicationtime.slice(0, 10)] = [];
                dataArr[x.medicationtime.slice(0, 10)].push(x);
            } else {
                dataArr[x.medicationtime.slice(0, 10)].push(x);
            }
        });

        var mainHtml = '';

        $.each(dataArr, function (m, n) {
            var html = '';
            var htmlHead = '';
            var htmlFoot = '';
            htmlHead = '<div class="section" data-time="' + m + '"><h4 class="caption">' + m + '</h4>' +
                '<div class="section-con">';
            htmlFoot = '</div></div>';
            $.each(n, function (k, v) {
                html += ' <div class="item">' +
                    '     <div class="typeImg"><img src="/images/Drug.png"></div>' +
                    '     <div class="item-r">' +
                    '         <div class="timeBox"><span class="time1">' + v.medicationtime.slice(11) + '</span><b>' + v.name + '</b><span' +
                    '                     class="time2">' + v.dose + ' mg</span>' +
                    '         </div>' +
                    '     </div>' +
                    ' </div>'
            });
            mainHtml += htmlHead + html + htmlFoot;


        });
        if (JSON.stringify(dataArr) == '{}') {
            $('#contentSwitch .Drug').html('<h4 style="text-align: center">暂无数据</h4>');
        } else {
            $('#contentSwitch .Drug').html(mainHtml);
        }
    } else {
        if($(".modal-dialog").css("display")!=='block'){
            alertModel('温馨提示', data.message)
        }

    }
};

function InsulinFun(data) {
    if (data.code = 10000) {
        // var dataArr = {'018-05-12': [{}, {}, {}], '018-05-13': [{}, {}, {}]};
        var dataArr = {};//用于存储整理过的数据对象（同一天放在一个对象中）
        $.each(data.data, function (z, x) {
            if (typeof (dataArr[x.medicationtime.slice(0, 10)]) == 'undefined') {//用于判断数组是否存在
                dataArr[x.medicationtime.slice(0, 10)] = [];
                dataArr[x.medicationtime.slice(0, 10)].push(x);
            } else {
                dataArr[x.medicationtime.slice(0, 10)].push(x);
            }
        });

        var mainHtml = '';

        $.each(dataArr, function (m, n) {
            var html = '';
            var htmlHead = '';
            var htmlFoot = '';
            htmlHead = '<div class="section" data-time="' + m + '"><h4 class="caption">' + m + '</h4>' +
                '<div class="section-con">';
            htmlFoot = '</div></div>';
            $.each(n, function (k, v) {
                html += ' <div class="item">' +
                    '     <div class="typeImg"><img src="/images/Insulin.png"></div>' +
                    '     <div class="item-r">' +
                    '         <div class="timeBox"><span class="time1">' + v.medicationtime.slice(11) + '</span><b>' + v.name + '</b><span' +
                    '                     class="time2">' + v.dose + ' u</span>' +
                    '         </div>' +
                    '     </div>' +
                    ' </div>'
            });
            mainHtml += htmlHead + html + htmlFoot;


        });
        if (JSON.stringify(dataArr) == '{}') {
            $('#contentSwitch .Insulin').html('<h4 style="text-align: center">暂无数据</h4>');
        } else {
            $('#contentSwitch .Insulin').html(mainHtml);
        }
    } else {
        if($(".modal-dialog").css("display")!=='block'){
            alertModel('温馨提示', data.message)
        }

    }
};

function motionFun(data) {
    if (data.code = 10000) {
        // var dataArr = {'018-05-12': [{}, {}, {}], '018-05-13': [{}, {}, {}]};
        var dataArr = {};//用于存储整理过的数据对象（同一天放在一个对象中）
        $.each(data.data, function (z, x) {
            if (typeof (dataArr[x.motiontime.slice(0, 10)]) == 'undefined') {//用于判断数组是否存在
                dataArr[x.motiontime.slice(0, 10)] = [];
                dataArr[x.motiontime.slice(0, 10)].push(x);
            } else {
                dataArr[x.motiontime.slice(0, 10)].push(x);
            }
        });
        var mainHtml = '';

        $.each(dataArr, function (m, n) {
            var html = '';
            var htmlHead = '';
            var htmlFoot = '';
            htmlHead = '<div class="section" data-time="' + m + '"><h4 class="caption">' + m + '</h4>' +
                '<div class="section-con">';
            htmlFoot = '</div></div>';
            $.each(n, function (k, v) {
                html += ' <div class="item">' +
                    '     <div class="typeImg"><img src="/images/motion.png"></div>' +
                    '     <div class="item-r">' +
                    '         <div class="timeBox"><span class="time1">' + v.motiontime.slice(11) + '</span><b>' + v.motiontype + '</b>' +
                    '<span class="time2">' + checkZero(v.stepsnum) + '步</span> ' +
                    ' <span class="time2">共' + checkZero(v.durationtime) + '分钟</span>' +
                    '         </div>' +
                    '     </div>' +
                    ' </div>'
            });
            mainHtml += htmlHead + html + htmlFoot;


        });
        if (JSON.stringify(dataArr) == '{}') {
            $('#contentSwitch .motion').html('<h4 style="text-align: center">暂无数据</h4>');
        } else {
            $('#contentSwitch .motion').html(mainHtml);
        }
    } else {
        if($(".modal-dialog").css("display")!=='block'){
            alertModel('温馨提示', data.message)
        }

    }
};

function checkZero(value) {
    if (value == 'null' || value == "" || value == null) {
        return 0
    } else {
        return value
    }
};


